﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace XServer.SDK
{
    using System;
    using System.Collections.Generic;
    using System.Threading;

    public class NonBlockingQueue<T>
    {
        public NonBlockingQueue() : this(128) { }

        public NonBlockingQueue(int INIT_COUNT = 128)
        {
            this.list.Capacity = INIT_COUNT;
        }

        public void Enqueue(T v)
        {
            lock (this)
            {
                list.Add(v);
            }
        }
        public bool Dequeue(ref List<T> v)
        {
            v.Clear();
            lock (this)
            {
                if (this.list.Count == 0) return false;
                Ext.Swap<List<T>>(ref this.list, ref v);
                this.list.Clear();
                return true;
            }
        }

        private List<T> list = new List<T>();
    }

    public class BlockingQueue<T>
    {
        public BlockingQueue() : this(128) { }
        public BlockingQueue(int INIT_COUNT = 128)
        {
            this.list.Capacity = INIT_COUNT;
        }

        public void Enqueue(T v)
        {
            lock (this)
            {
                list.Add(v);
                Monitor.Pulse(this);
            }
        }

        public void Enqueue(List<T> v)
        {
            lock (this)
            {
                list.AddRange(v);
                Monitor.Pulse(this);
            }
        }

        public bool Dequeue(ref List<T> v)
        {
            lock (this)
            {
                while (list.Count == 0) Monitor.Wait(this);
                Ext.Swap<List<T>>(ref this.list, ref v);
                this.list.Clear();
                return true;
            }
        }

        private List<T> list = new List<T>();
    }
}
